module.exports = app => {
    const express = require('express')
    const customer = require('../../models/customer')
    const router = express.Router({
        mergeParams: true
    })
    
    router.get('/allservice',async(req,res)=>{
      await customer.find({status:'3'},(err,data)=>{
        let a = []
        data.filter(item=>{
          return a.push(item.default_address)
        })
        err ? res.send('服务器错误...') : res.send(a)
      })
    })

    router.get('/customer',async(req,res)=>{
      await customer.find({status:'3'}, (err,data)=>{
        var datas = []
        data.forEach(e=>{
          // if(e.default_address[0].area == req.query.address){
            datas.push(e.default_address[0].service)
          // }
        })
        err ? res.send('服务器错误...') : res.send(datas)
      })
    })
    router.get('/address',async(req,res)=>{
        const token = req.query.token
        await customer.findOne({token:token}, (err,data)=>{
          err ? res.send('服务器错误...') : res.send(data.address)
        })
    })

    router.post('/address',async(req,res) => {
      const { token, address } = req.body
      // if(address.default){
      //   await customer.updateOne({ token: token, 'address.default': true }, {$set: {'address.$.default':false}}, err=>{
      //     err ? res.send('服务器错误...') : res.send('ok')
      //   })
      // }
      await customer.updateOne({ token: token }, { $addToSet: { address: address }}, err=>{
        err ? res.send('服务器错误...') : res.send('ok')
      })
    })

    router.delete('/address',async(req,res) => {
      const { token, _id } = req.body
      await customer.findOneAndUpdate({ token: token }, { $pull: { address:{_id: _id} } }, {new:true},(err, data)=>{
        err ? res.send('服务器错误...') : res.send(data.address)
      })
    })
    
    router.put('/address',async(req,res)=>{
      const { token, address, _id } = req.body
      // if(address.default){
      //   await customer.updateOne({ token: token, 'address._id': {$ne:_id} }, {$set: {'address.$.default':false}}, err=>{
      //     err ? res.send('服务器错误...') : res.send('ok')
      //   })
      // }
      await customer.updateOne({ token: token,'address._id': _id }, {$set: {'address.$':address}}, (err,a)=>{
        err ? res.send('服务器错误...') : res.send('ok')
      })
    })

    app.use('/api/admin',router)
}